<template>
  <div>
    <el-dialog
      :title="type==='add'?'新增会员卡':'编辑会员卡'+'：'+name"
      :visible.sync="dialogVisible"
      fullscreen
      :close-on-click-modal="false"
      center
      @close="close"
    >
      <el-form
        ref="form"
        v-loading="loading"
        :model="form"
        :rules="rules"
        class="content"
        label-width="100px"
        size="small"
      >
        <!-- 卡面 -->
        <el-form-item label="卡面：" prop="cardImage">
          <div class="flexRSC">
            <el-upload
              class="app-uploader-img-plus"
              :action="actionUrl"
              :show-file-list="false"
              :headers="uploadHeaders"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.cardImage" :src="fileBaseUrl+form.cardImage" class="avatar">
              <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
            </el-upload>
            <ul class="upload-tips">
              <li>图片要求：</li>
              <li>1.上传的图片大小不超过1MB，仅支持JPG/PNG格式</li>
              <li>2.像素大小控制在1000像素*600像素以下</li>
              <li>
                <el-button size="small" @click="openCardImgMap ">从系统图库中选择</el-button>
              </li>
            </ul>
          </div>
        </el-form-item>

        <!-- 卡名称 -->
        <el-form-item label="卡名称：" prop="categoryName">
          <el-input
            v-model="form.categoryName"
            placeholder="请输入卡名称"
            clearable
            class="input-append-400"
          />
        </el-form-item>
        <el-form-item label="背景颜色">
          <el-color-picker v-model="form.backgroundColor"></el-color-picker>
        </el-form-item>

        <!-- 开卡门槛 -->
        <el-form-item label="开卡门槛" prop="payType">
          <div style="margin-bottom:18px">
            <el-radio v-model="form.payType" :label="1">无门槛开卡，顾客领卡即开通</el-radio>
          </div>
          <div>
            <el-radio v-model="form.payType" :label="2">支付一定费用开卡，开卡费为&nbsp;&nbsp;</el-radio>
            <el-form-item prop="payCost" style="display:inline-block">
              <el-input
                v-model="form.payCost"
                :disabled="form.payType!==2"
                maxlength="10"
                class="input-append-240"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
          <!-- 开卡费工本费 -->
          <div>
            <el-collapse-transition>
              <el-card v-if="form.payType===2" class="nest-card-box" style="margin-bottom:18px;">
                <div>开卡费即会员卡的工本费，在顾客首次开卡的时候需要支付，注意区分开卡费与年费：</div>
                <el-form-item prop="enablePayDifference">
                  <el-checkbox
                    v-model="form.enablePayDifference"
                  >升级到该卡时支持差额升级，需支付原会员卡与当前会员卡的开卡费的差额升级</el-checkbox>
                </el-form-item>
              </el-card>
            </el-collapse-transition>
          </div>
          <div>
            <el-radio v-model="form.payType" :label="3">充值一定的金额即可开卡，最低需要充值&nbsp;&nbsp;</el-radio>
            <el-form-item prop="rechargeCost" style="display:inline-block">
              <el-input
                v-model="form.rechargeCost"
                :disabled="form.payType!==3"
                maxlength="10"
                class="input-append-240"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
          <div>
            <el-radio v-model="form.payType" :label="4">仅可客服人工开卡</el-radio>
          </div>
        </el-form-item>

        <!-- 有效期 -->
        <el-form-item label="有效期：" prop="validPeriod">
          <el-radio v-model="validPeriodRadio" :label="1">永久有效</el-radio>
          <br>
          <el-radio v-model="validPeriodRadio" :label="2">领卡日起&nbsp;&nbsp;</el-radio>
          <el-input
            v-model="form.validPeriod"
            :disabled="validPeriodRadio===1"
            class="input-append-308"
            maxlength="3"
          >
            <template slot="append">年</template>
          </el-input>
        </el-form-item>

        <!-- 年费 -->
        <el-form-item label="年费：" class="is-required">
          <div>
            <el-radio
              v-model="form.annualFeeRadio"
              :label="1"
              :disabled="validPeriodRadio===1||form.payType===1"
            >无年费</el-radio>
          </div>
          <div>
            <el-radio
              v-model="form.annualFeeRadio"
              :label="2"
              :disabled="validPeriodRadio===1||form.payType===1"
            >每年需缴纳年费&nbsp;&nbsp;</el-radio>
            <el-form-item prop="annualFee" style="display:inline-block">
              <el-input
                v-model="form.annualFee"
                :disabled="form.annualFeeRadio===1"
                maxlength="10"
                class="input-append-308"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
          <el-card class="nest-card-box">
            <div>年费是会员卡的每年定期付费项目，顾客只有支付了年费才可以维持会员卡的可用状态，否则会员卡将会在有效期最后一天的24:00失效</div>
            <el-checkbox
              v-model="form.firstYearFree"
              :disabled="form.annualFeeRadio===1"
              style="height:20px;line-height:20px"
            >开卡免首年年费</el-checkbox>
            <br>
            <el-checkbox
              v-model="form.autoRenew"
              :disabled="form.annualFeeRadio===1"
              style="height:20px;line-height:20px"
            >会员卡即将过期时（过期当天）从会员的余额直接扣除年费</el-checkbox>
            <br>
            <el-checkbox
              v-model="form.enableAnnualfeeDifference"
              :disabled="form.annualFeeRadio===1"
              style="height:20px;line-height:20px"
            >升级卡时支持差额升级，需支付原会员卡与当前会员卡的年费的差额升级</el-checkbox>
          </el-card>
        </el-form-item>

        <!-- 高级使用限制 -->
        <el-form-item label="使用限制：" class="use-limit-box">
          <el-switch v-model="form.hasUseLimit" :disabled="form.payType!==4" />
          <span>（仅人工开卡可配置）</span>
          <el-collapse-transition>
            <el-card v-if="form.payType===4&&form.hasUseLimit">
              <div
                style="line-height:30px"
              >使用限制是为了满足一些商业合作场景, 比如商户通过赠予其他企业此类会员卡, 但商户可以对其设置一些特殊的使用规则, 区别于正常注册的会员, 开启后你可以勾选以下特殊规则:</div>
              <el-checkbox
                v-model="useLimitRuleForm.allowRecharge"
              >此卡不允许顾客线上充值或者POS机等线下充值 ( 注意: 不影响商户后台修改会员卡余额 )</el-checkbox>
              <br>
              <el-checkbox
                v-model="useLimitRuleForm.allowChangeCategory"
              >此卡顾客可以自助在小程序升级/降级到其他会员卡( 注意: 顾客升级到其他会员卡后此卡的过期规则将永久不会生效 )</el-checkbox>
              <br>
              <el-checkbox
                v-model="useLimitRuleForm.balanceClearChange"
                :disabled="!useLimitRuleForm.allowChangeCategory"
              >
                此卡顾客升级/降级到其他会员卡会自动清零现有
                <span style="color:red">实充账户</span>的余额
              </el-checkbox>
              <br>
              <el-checkbox
                v-model="useLimitRuleForm.giftClearChange"
                :disabled="!useLimitRuleForm.allowChangeCategory"
              >
                此卡顾客升级/降级到其他会员卡会自动清零现有
                <span style="color:red">赠送账户</span>的余额
              </el-checkbox>
              <br>
              <el-checkbox
                v-model="useLimitRuleForm.allowRenewCard"
              >此卡过期后该卡会员不可续费 ( 注意: 不影响顾客重新开通其他会员卡 )</el-checkbox>
              <br>
              <el-checkbox v-model="useLimitRuleForm.balanceClearExpire">
                此卡过期后该会员的
                <span style="color:red">实充余额</span>自动清零
              </el-checkbox>
              <br>
              <el-checkbox v-model="useLimitRuleForm.giftClearExpire">
                此卡过期后该会员的
                <span style="color:red">赠送余额</span>自动清零
              </el-checkbox>
              <div style="line-height:30px">以上特殊规则会对会员卡的使用有非常大的使用限制, 请谨慎勾选且在顾客开卡时做好沟通!!!</div>
            </el-card>
          </el-collapse-transition>
        </el-form-item>
        <el-form-item label="使用说明：" prop="instructions">
          <el-card>
            <!-- <ul class="instructions-list">
              <li v-if="instructionsArray.length==0">暂无使用说明</li>
              <li
                v-for="(instructionsArrayItem,index) in instructionsArray"
                :key="index"
              >{{index+1}}.{{instructionsArrayItem}}</li>
            </ul>
            <div>额外说明：</div>-->
            <el-input
              v-model="form.instructions"
              type="textarea"
              :autosize="{ minRows: 5}"
              placeholder="请输入"
            />
          </el-card>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button round size="small" @click="hide">取 消</el-button>
        <el-button :disabled="loading" type="primary" round size="small" @click="save">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 图库 -->
    <card-img-map ref="cardImgMap" img-type="卡面" />
  </div>
</template>

<script>
import { imgUploadUrl } from '@/api/upload'
import { mapGetters } from 'vuex'
import { getVipCardInfo, checkCardName, editVipCard } from '@/api/vip'
import {
  validateMoney,
  validateStrLen,
  validatePositiveInt
} from '@/utils/validate.js'
export default {
  data() {
    /**
       * 表单校验方法
       */
    const validateRmb = (rule, value, callback, text) => {
      if (value === '') {
        callback(new Error(text))
      } else if (!validateMoney(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }

    // 卡名称 9个汉字18个字符
    const validateCategoryName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入卡名称'))
      } else if (!validateStrLen(value, 18)) {
        callback(new Error('长度不超过9个汉字或18个字符'))
      } else if (
        this.type === 'edit' &&
          this.categoryName === this.form.categoryName
      ) {
        callback()
      } else {
        checkCardName(value)
          .then(res => {
            callback()
          })
          .catch(err => {
            callback(new Error('卡名称重复'))
          })
      }
    }

    //  开卡费
    const validatePayCost = (rule, value, callback) => {
      if (this.form.payType === 2) {
        if (value === '') {
          callback(new Error('请输入开卡费'))
        } else if (!validateMoney(value)) {
          callback(new Error('请输入整数，正小数（小数位不超过2位）'))
        } else if (value - 999999.99 > 0) {
          callback('超过限额999999.99')
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    // 充值
    const validateRechargeCost = (rule, value, callback) => {
      if (this.form.payType === 3) {
        validateRmb(rule, value, callback, '请输入充值金额')
      } else {
        callback()
      }
    }

    // 有效期
    const validateValidPeriod = (rule, value, callback) => {
      if (this.validPeriodRadio === 1) {
        callback()
      } else if (value === '') {
        callback(new Error('请输入有效期年(1~100正整数)'))
      } else if (!validatePositiveInt(value, 100)) {
        callback(new Error('请输入有效期年(1~100正整数)'))
      } else {
        callback()
      }
    }

    // 年费
    const validateAnnualFee = (rule, value, callback) => {
      if (this.form.annualFeeRadio === 1) {
        callback()
      } else {
        if (value === '') {
          callback(new Error('请输入年费'))
        } else if (!validateMoney(value)) {
          callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
        } else if (value - 999999.99 > 0) {
          callback('超过限额999999.99')
        } else if (
          this.form.payType === 3 &&
            this.form.rechargeCost &&
            validateMoney(this.form.rechargeCost)
        ) {
          // 判断年费不可以大于充值
          value - this.form.rechargeCost > 0 && !this.form.firstYearFree
            ? callback(new Error('每年需缴纳年费不得大于最低充值金额'))
            : callback()
        } else {
          callback()
        }
      }
    }

    // 自定义使用说明
    const validateInstructions = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!validateStrLen(value, 200)) {
        callback(new Error('长度不超过200个汉字或400个字符'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        cardImage: [
          {
            required: true,
            message: '请上传或者选择卡面',
            trigger: ['change']
          }
        ],
        // 1.卡名称
        categoryName: [
          {
            required: true,
            validator: validateCategoryName,
            trigger: ['blur']
          }
        ],
        // 开卡门槛
        payType: [
          {
            required: true,
            message: '请选择开卡门槛',
            trigger: ['change']
          }
        ],
        // 开卡费
        payCost: [
          {
            required: true,
            validator: validatePayCost,
            trigger: ['blur']
          }
        ],
        // 开卡充值
        rechargeCost: [
          {
            required: true,
            validator: validateRechargeCost,
            trigger: ['blur']
          }
        ],
        // 有效期
        validPeriod: [
          {
            required: true,
            validator: validateValidPeriod,
            trigger: ['blur']
          }
        ],
        // 年费
        annualFee: [
          {
            required: true,
            validator: validateAnnualFee,
            trigger: ['blur', 'change']
          }
        ],
        instructions: [
          {
            validator: validateInstructions,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      uploadHeaders: {}, // 上传请求头
      actionUrl: imgUploadUrl, // 上传地址
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      type: '',
      cardOrder: '',
      id: '',
      name: '',
      validPeriodRadio: 1, // 有效期单选状态
      categoryName: '', // 卡名称
      instructions: '',
      form: {
        backgroundColor: '#fff',
        annualFeeRadio: 1, // not params 年费单选状态
        cardOrder: 1, // 卡序
        payType: 1, // 开卡方式
        cardImage: '', // 1. 卡背景图
        categoryName: '', // 卡名称
        payCost: '', // 开卡费用x100
        rechargeCost: '', // 开卡充值金额x100
        validPeriod: '', // 有效期
        annualFee: '', // 年费x100
        firstYearFree: true,
        autoRenew: true, // 自动扣年费
        enableAnnualfeeDifference: true, // 差额升级
        hasUseLimit: false, // 是否开启高级限制
        instructions: ''
      },
      useLimitRuleForm: {
        allowRecharge: false,
        allowChangeCategory: false,
        balanceClearChange: false,
        giftClearChange: false,
        allowRenewCard: false,
        balanceClearExpire: false,
        giftClearExpire: false
      }
    }
  },
  watch: {
    // 有效期单选改变
    validPeriodRadio(val) {
      if (val === 1) {
        // 永久有效则重置年费等信息
        this.form.annualFeeRadio = 1
        // 清除校验
        this.$refs.form.clearValidate(['validPeriod'])
      }
    },
    form: {
      handler: function(val) {
        // 开卡门槛改变
        if (val.payType === 1) {
          val.annualFeeRadio = 1
        }
        if (val.payType !== 2) {
          this.$refs.form.clearValidate(['payCost'])
        }
        if (val.payType !== 3) {
          this.$refs.form.clearValidate(['rechargeCost'])
        }
        if (val.payType !== 4) {
          this.form.hasUseLimit = false
        }

        // 年费单选改变
        if (val.annualFeeRadio === 1) {
          this.$refs.form.clearValidate(['annualFee'])
        } else {
          this.$refs.form.validateField('annualFee')
        }
      },
      deep: true
    },
    useLimitRuleForm: {
      handler: function(val) {
        if (val.allowChangeCategory === false) {
          val.balanceClearChange = false
          val.giftClearChange = false
        }
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  mounted() {},
  methods: {
    /**
       * 弹框相关
       */
    open({
      type = 'add',
      cardOrder = '',
      id = '',
      name = '',
      instructions = ''
    }) {
      this.type = type
      this.cardOrder = cardOrder
      this.id = id
      this.name = name
      this.instructions = instructions
      if (type === 'edit' && id !== '') {
        this.initData(id)
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      // Object.assign(this.$data, this.$options.data());
      this.loading = false
      this.useLimitRuleForm = {
        allowRecharge: false,
        allowChangeCategory: false,
        balanceClearChange: false,
        giftClearChange: false,
        allowRenewCard: false,
        balanceClearExpire: false,
        giftClearExpire: false
      }
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },

    hide() {
      this.dialogVisible = false
    },

    /**
       *  获取数据
       */
    // 获取表单数据
    initData(id) {
      this.loading = true
      getVipCardInfo(id)
        .then(res => {
          // 重置回表单数据
          this.categoryName = res.data.basicInfo.categoryName
          this.resetData(res.data.basicInfo)
          if (res.data.basicInfo.hasUseLimit) {
            this.resetEnterpriseLimitForm(res.data.useLimitRule)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 重置enterpriseLimitCard数据
    resetEnterpriseLimitForm(data) {
      if (data) {
        data.allowRecharge = !data.allowRecharge
        data.allowRenewCard = !data.allowRenewCard
        this.useLimitRuleForm = data
      }
    },

    // 格式化数据
    resetData(data) {
      switch (data.payType) {
        case 1:
          data.rechargeCost = ''
          data.payCost = ''
          break
        case 2:
          data.rechargeCost = ''
          data.payCost = data.payCost / 100 // 换算元
          break
        case 3:
          data.payCost = ''
          data.rechargeCost = data.rechargeCost / 100 // 换算元
          break
        case 4:
          data.rechargeCost = ''
          data.payCost = ''
          break
      }

      if (data.annualFee === 0) {
        data.annualFeeRadio = 1
        data.annualFee = ''
      } else {
        data.annualFeeRadio = 2
        data.annualFee = data.annualFee / 100 // 换算元
      }

      if (data.validPeriod === 0) {
        this.validPeriodRadio = 1
        data.validPeriod = ''
      } else {
        this.validPeriodRadio = 2
      }
      data.instructions = this.instructions
      this.form = data
    },

    /**
       * 按钮组
       */
    // 点击下一步 保存数据
    save() {
      this.$refs.form.validate(valid => {
        const data = JSON.parse(JSON.stringify(this.form))
        console.log(data)
        if (valid) {
          switch (data.payType) {
            case 1:
              data.payCost = 0
              data.rechargeCost = 0
              break
            case 2:
              data.rechargeCost = 0
              break
            case 3:
              data.payCost = 0
              break
            case 4:
              data.payCost = 0
              data.rechargeCost = 0
              break
          }
          data.payCost = this.$math.mul(data.payCost, 100, 0) // 换算分
          data.rechargeCost = this.$math.mul(data.rechargeCost, 100, 0) // 换算分

          // 无年费 设置0
          if (data.annualFeeRadio === 1) {
            data.annualFee = 0
          } else {
            data.annualFee = this.$math.mul(data.annualFee, 100, 0) // 换算分
          }
          delete data.annualFeeRadio

          // 永久有效 设为0
          if (this.validPeriodRadio === 1) {
            data.validPeriod = 0
          }

          let useLimitRuleForm = Object.assign({}, this.useLimitRuleForm)
          useLimitRuleForm.allowRecharge = !useLimitRuleForm.allowRecharge
          useLimitRuleForm.allowRenewCard = !useLimitRuleForm.allowRenewCard

          // 去除限制
          if (!data.hasUseLimit) {
            useLimitRuleForm = null
          }
          const params = {}
          params.basic = data
          params.useLimitRule = useLimitRuleForm
          if (this.type === 'add') {
            params.basic.cardOrder = this.cardOrder
            params.award = {
              giftBalance: 0,
              giftPoints: 0,
              couponAward: [],
              customGift: ''
            }
            params.rights = {
              categoryDiscount: 100,
              rechargeAwardInfo: [],
              multiplePoints: 10,
              customBenefit: ''
            }
            params.explain = { instructions: data.instructions, privilege: '' }
          } else {
            params.id = this.id
            params.explain = { instructions: data.instructions }
          }

          this.loading = true
          editVipCard(this.type === 'add' ? 'post' : 'put', params)
            .then(res => {
              this.$notify({
                title: '成功',
                message: `${this.type === 'add' ? '新增成功' : '更新成功'}`,
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.hide()
              this.resolve && this.resolve()
            })
            .catch(err => {})
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.cardImage = res.data.path
        this.$refs.form.clearValidate(['cardImage'])
      } else {
        this.$message.error(res.msg)
      }
    },

    // 处理图片上传前
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 1000, 600, 1)
    },

    // 打开图库
    openCardImgMap() {
      this.$refs.cardImgMap.open().then(res => {
        this.form.cardImage = res
        this.$refs.form.clearValidate(['cardImage'])
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .content {
    margin: 0 auto;
    width: 60%;
    min-width: 800px;
    max-width: 900px;
  }
  /* 输入框长度 */
  .input-append-308 {
    width: 308px;
  }
  .input-append-240 {
    width: 240px;
  }
  .input-append-400 {
    width: 400px;
  }

  /* 内层嵌套卡片 */
  .nest-card-box {
    margin-left: 24px;
  }

  /* 上传 */
  .app-uploader-img-plus {
    width: 300px;
    height: 180px;
    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 300px;
      height: 180px;
      line-height: 170px;
      text-align: center;
    }
    .avatar {
      width: 300px;
      height: 180px;
      display: block;
    }
  }
  .upload-tips {
    margin-left: 20px;
    li {
      margin-top: 10px;
      font-size: 14px;
      line-height: 16px;
      color: $dark-font-color;
    }
  }
  /* 使用说明 */
  .instructions-list {
    li {
      line-height: 30px;
    }
  }
</style>
